package com.bjpowernode.controller;

import com.bjpowernode.beans.Remark;
import com.bjpowernode.beans.User;
import com.bjpowernode.dto.ResultDTO;
import com.bjpowernode.exception.CRUDException;
import com.bjpowernode.services.RemarkServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/ActivitiesRemark")
public class ActivitiesRemarkController {


    @Autowired
    RemarkServices remarkServices;

    @RequestMapping("add.action")
    public ResultDTO add(Remark remark, HttpSession httpSession) throws CRUDException {
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);
        remark.setNotePerson(((User) httpSession.getAttribute("user")).getName());
        if (!remarkServices.add(remark)) {
            throw new CRUDException("备注添加失败,影响行数为0");
        }
        return resultDTO;
    }

    @RequestMapping("del.action")
    public ResultDTO del(String id) throws CRUDException {
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);

        if (!remarkServices.del(id)) {
            throw new CRUDException("备注删除失败,影响行数为0");
        }
        return resultDTO;
    }

    @RequestMapping("edit.action")
    public ResultDTO edit(Remark remark,HttpSession httpSession) throws CRUDException {
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(ResultDTO.SUCCESS);

        //按照ID查询备注
        Remark remarkTemp = remarkServices.get(remark.getId());
        User user = (User)httpSession.getAttribute("user");
        if(!remarkTemp.getNotePerson().equals(user.getName())){
            throw new CRUDException("你不是添加该备注的用户，无法修改");
        }
        if (!remarkServices.edit(remark)) {
            throw new CRUDException("备注修改失败,影响行数为0");
        }
        return resultDTO;
    }


}
